<?php
/**
 * Note: *
 */

namespace App\Handlers;

use App\Constants\WechatConstant;
use App\Http\Controllers\Admin\LoginController;
use App\Http\Controllers\Admin\ManagerController;
use App\Services\GatewayWorkerService;
use App\Services\Wechat\OfficialAccountService;
use EasyWeChat\Kernel\Support\Collection;
use Illuminate\Support\Str;

class WechatEventMessageHandler implements \EasyWeChat\Kernel\Contracts\EventHandlerInterface
{
    /**
     * @var Collection|null
     */
    protected $payload = null;

    protected $openid = '';

    public function handle($payload = null)
    {
        $this->payload = $payload;

        $this->openid = $payload->FromUserName;

        // 关注
        if ($this->payload->Event === 'subscribe') {
            return $this->subscribe();

        }
        if ($this->payload->Event === 'unsubscribe') {
            return $this->unsubscribe();
        }

        if ($this->payload->Event === 'SCAN') {
            return $this->scan();
        }
    }

    /**
     * 订阅消息
     */
    private function subscribe()
    {
        // 带参数二维码, EventKey = qrscene_事件ID
        if (Str::startsWith($this->payload->EventKey, 'qrscene_')) {
            return $this->scan();
        }
        return 'ok';
    }

    /**
     * 取消订阅
     */
    private function unsubscribe()
    {
        return 'ok';
    }

    /**
     * 扫码事件
     * 二维码内容在缓存中
     * @return string
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    private function scan()
    {
        if (Str::startsWith($this->payload->EventKey, 'qrscene_')) {
            $event = (int) str_replace('qrscene_', '', $this->payload->EventKey);
        } else {
            $event = (int) $this->payload->EventKey;
        }

        $ticket = $this->payload->Ticket;

        $service = new OfficialAccountService();
        $qrcodeInfo = $service->getQrcodeInfo($ticket);

        // 后台管理员登录, 存储openid, 通知客户端处理
        if ($event === WechatConstant::EVENT_ADMIN_LOGIN) {
            try {
                app(LoginController::class)->loginQrcodeReceive(WechatConstant::NAME, $this->openid, $qrcodeInfo);
                return '操作成功';
            } catch (\Exception $e) {
                return $e->getMessage();
            }
        }
        // 后台管理员绑定微信
        if ($event === WechatConstant::EVENT_ADMIN_BIND) {
            try {
                $res = app(ManagerController::class)->bindQrcodeReceive(WechatConstant::NAME, $this->openid, $qrcodeInfo);
                return $res ? '绑定成功' : '绑定失败';
            } catch (\Exception $e) {
                return $e->getMessage();
            }
        }
    }
}
